<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path:'/blank' }"><i class="el-icon-notebook-2"></i>考试管理</el-breadcrumb-item>
      <el-breadcrumb-item>试题管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <!--搜索栏-->
    <el-row style="text-align: left">
      <el-select v-model="queryInfo.quType" clearable placeholder="请选择题目类型" @visible-change="questionList">
        <el-option v-for="item in quType" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-select v-if="bankId==0" v-model="queryInfo.quBankId" clearable placeholder="请选择题库" style="margin: 0 5px"
                 @visible-change="questionList">
        <el-option v-for="item in allBank" :key="item.id" :label="item.bankName" :value="item.bankId"></el-option>
      </el-select>
      <el-select v-else v-model="bankName" clearable placeholder="请选择题库" :disabled="isBank" style="margin: 0 5px"
                 @visible-change="questionList">
        <el-option v-for="item in allBank" :key="item.id" :label="item.bankName" :value="item.bankId"></el-option>
      </el-select>
      <el-input v-model="queryInfo.quContent" placeholder="请输入内容" prefix-icon="el-icon-search"
                @keydown.native.enter="questionList"
                style="width: 220px;margin-right: 10px"></el-input>
      <el-button type="success" size="medium" icon="el-icon-search" @click="questionList">搜索</el-button>
      <el-button type="warning" size="medium" v-if="isBank" style="float: right;margin-right: 20px"
                 @click="$router.push('/bank')">返回题库
      </el-button>
    </el-row>
    <!--操作的下拉弹框-->
    <el-row v-if="selectionTable.length !== 0">
      <el-select v-model="operation" :placeholder="'已选择' + selectionTable.length + '项'"
                 clearable style="float: left;margin: 10px 0" @change="operationChange">
        <el-option v-for="(item,index) in optionInfo1" :key="index" :value="item.desc">
          <span style="float: left">{{ item.label }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.desc }}</span>
        </el-option>
      </el-select>
    </el-row>
    <!--添加题目按钮-->
    <el-row style="margin: 10px 0;text-align: left" v-else>
      <el-button icon="el-icon-plus" type="primary" size="medium" @click="addTopic">添加题目</el-button>
    </el-row>
    <!--添加题目-->
    <el-dialog :visible.sync="addNewTopice" center title="添加题目" width="50%" style="margin-top: -100px" :before-close="beforeClose">
      <el-card>
        <el-form ref="formName" :model="formName" :rules="formRules">
          <el-form-item label="题目类型" label-width="120px" prop="quType">
            <el-select v-model="formName.quType" placeholder="请选择">
              <el-option v-for="item in quType" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="难度等级" label-width="120px" prop="level">
            <el-select v-model="formName.level" placeholder="请选择">
              <el-option :value="parseInt(1)" label="简单"></el-option>
              <el-option :value="parseInt(2)" label="中等"></el-option>
              <el-option :value="parseInt(3)" label="困难"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="归属题库" label-width="120px" prop="quBankId">
            <el-select v-model="formName.quBankId" placeholder="请选择">
              <el-option v-for="item in allBank" :key="item.bankId" :label="item.bankName"
                         :value="item.bankId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题目内容" label-width="120px" prop="quContent">
            <el-input v-model="formName.quContent" :rows="2" style="margin-left: 5px" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="题目图片" label-width="120px">
            <el-upload action="http://localhost:9285/resource/upload/image" :on-success="handleSuccess" clearFiles
                       :on-preview="handlePreview" :on-remove="handleRemove" multiple :before-remove="beforeRemove"
                       :limit="2" :file-list="answerFile">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" style="margin: 0;padding: 0;color: red">温馨提示: 只能上传jpg/png文件,禁止上传本题无关图片</div>
            </el-upload>
            <!--答案图片-->
            <div v-show="answerUrl">
              <el-image :src="answerImage"></el-image>
            </div>
          </el-form-item>
          <el-form-item label="整题解析" label-width="120px" prop="analysis">
            <el-input v-model="formName.analysis" :rows="2" style="margin-left: 5px" type="textarea"></el-input>
          </el-form-item>
          <el-button v-if="formName.quType!==4" icon="el-icon-plus" plain size="small"
                     style="margin-left: 40px" type="primary" @click="addAnswer">添加
          </el-button>
          <!--存放答案表单的信息-->
          <el-form-item v-if="formName.quType !== 4" prop="answer">
            <el-table :data="answers" border style="width: 96%;margin-left: 40px;margin-top: 10px">
              <el-table-column align="center" label="是否答案" width="80">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.isTrue" @change="checked=>checkAnswer(checked,scope.row.id)">答案
                  </el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="答案图片" align="center" width="120">
                <el-button size="small" type="primary" @click="developed">点击上传</el-button>
              </el-table-column>
              <el-table-column label="答案内容" header-align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.answerOne" :rows="2" style="margin-left: 5px" type="textarea"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="答案解析" header-align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.analysis" :rows="2" style="margin-left: 5px" type="textarea"></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="80">
                <template slot-scope="scope">
                  <el-button circle icon="el-icon-delete" type="danger" @click="delAnswer(scope.row.id)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </el-card>
      <div style="margin: 10px 0">
        <el-button type="primary" @click="submitForm('formName')">添加</el-button>
        <el-button type="info" @click="resetForm('formName')">重置</el-button>
        <el-button type="warning" @click="beforeClose(0)">取消</el-button>
      </div>
    </el-dialog>
    <!--显示题目和内容-->
    <el-table :border="true" :data="questionInfo" @selection-change="handleTableSectionChange">
      <el-table-column type="selection" width="60" align="center"></el-table-column>
      <el-table-column label="题目类型" width="150px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.quType === 1">单选题</span>
          <span v-else-if="scope.row.quType === 2">多选题</span>
          <span v-else-if="scope.row.quType === 3">判断题</span>
          <span v-else-if="scope.row.quType === 4">简答题</span>
        </template>
      </el-table-column>
      <el-table-column label="题目内容" prop="quContent" header-align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span @click="updateQu(scope.row)" style="cursor: pointer;">{{ scope.row.quContent }}</span>
        </template>
      </el-table-column>
      <el-table-column label="难度等级" width="150px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.level === 1">简单</span>
          <span v-if="scope.row.level === 2">中等</span>
          <span v-if="scope.row.level === 3">困难</span>
        </template>
      </el-table-column>
      <el-table-column label="所属题库" prop="bankName" width="150px" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column label="创建人" prop="userTrueName" width="150px" align="center"
                       show-overflow-tooltip></el-table-column>
      <el-table-column label="修改时间" prop="gmtModified" width="180px" align="center"></el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" size="mini" type="primary" circle @click="updateQu(scope.row)"></el-button>
          <el-button icon="el-icon-delete" size="mini" type="danger" circle
                     @click="handleDelete(scope.row.id)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div style="text-align: right;margin: 10px auto">
      <el-pagination @current-change="changePage" layout="total,prev, pager, next" :total="total"
                     :current-page="currentPage" :page-size="pageSize"></el-pagination>
    </div>
    <!--更新题目弹框-->
    <el-dialog :visible.sync="updateQuTableVisible" center title="更新题目" width="50%" :before-close="beforeClose">
      <el-card>
        <el-form ref="updateQuestionForm" :model="updateQuestionForm" :rules="updateQuestionFormRules">
          <el-form-item label="题目类型" label-width="120px" prop="quType">
            <el-select v-model="updateQuestionForm.quType" :disabled="isEdit" placeholder="请选择">
              <el-option v-for="item in quType" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="难度等级" label-width="120px" prop="level">
            <el-select v-model="updateQuestionForm.level" placeholder="请选择">
              <el-option :value="parseInt(1)" label="简单"></el-option>
              <el-option :value="parseInt(2)" label="中等"></el-option>
              <el-option :value="parseInt(3)" label="困难"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="归属题库" label-width="120px" prop="quBankId">
            <el-select v-model="updateQuestionForm.quBankId" placeholder="请选择">
              <el-option v-for="item in allBank" :key="item.bankId" :label="item.bankName"
                         :value="item.bankId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题目内容" label-width="120px" prop="quContent">
            <el-input v-model="updateQuestionForm.quContent" :rows="2" style="margin-left: 5px"
                      type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="题目图片" label-width="120px">
            <el-upload action="http://localhost:9285/resource/upload/image" :on-success="handleSuccess" clearFiles
                       :on-preview="handlePreview" :on-remove="handleRemove" multiple :before-remove="beforeRemove"
                       :limit="2" :file-list="answerFile">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" style="margin: 0;padding: 0;color: red">温馨提示: 只能上传jpg/png文件,禁止上传本题无关图片</div>
            </el-upload>
            <!--答案图片-->
            <div v-show="answerUrl">
              <el-image :src="answerImage"></el-image>
            </div>
          </el-form-item>
          <el-form-item label="整题解析" label-width="120px" prop="analysis">
            <el-input v-model="updateQuestionForm.analysis" :rows="2" style="margin-left: 5px"
                      type="textarea"></el-input>
          </el-form-item>
          <el-button v-if="updateQuestionForm.quType!==4" icon="el-icon-plus" plain size="small"
                     style="margin-left: 40px" type="primary" @click="addUpdateAnswer">添加
          </el-button>
          <!--存放答案表单的信息-->
          <el-form-item v-if="updateQuestionForm.quType !== 4" prop="answer">
            <el-table :data="updateAnswers" border style="width: 96%;margin-left: 40px;margin-top: 10px">
              <el-table-column align="center" label="是否答案" width="80">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.isTrue" @change="checked=>checkAnswer(checked,scope.row.id)">答案
                  </el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="答案图片" align="center" width="120">
                <el-button size="small" type="primary" @click="developed">点击上传</el-button>
              </el-table-column>
              <el-table-column label="答案内容" header-align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.answerOne" :rows="2" style="margin-left: 5px" type="textarea"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="答案解析" header-align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.analysis" :rows="2" style="margin-left: 5px" type="textarea"></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="80">
                <template slot-scope="scope">
                  <el-button circle icon="el-icon-delete" type="danger"
                             @click="delUpdateAnswer(scope.row.id)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateQuestion('updateQuestionForm')">确 定</el-button>
        <el-button type="warning" @click="beforeClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      bankId:'',
      //当前用户信息
      localUser:{},
      //装图片的
      answerFile: [],
      answerImage: '',
      //数据库中查询全部的题目
      questionInfo: [],
      total: 0,
      pageSize: 0,
      currentPage: 1,
      //表格行被选中后的数据
      operation: '',
      //表格被选中的所有行
      selectionTable: [],
      //数据中查询的题库信息
      allBank: [],
      isEdit: false,
      isBank: false,
      //弹框
      answerUrl: false,
      addQuTableVisible: false,
      updateQuTableVisible: false,
      addNewTopice: false,
      //用来从题库跳到题目中在下拉选显示题库名称
      bankName:"",
      //题目类型下拉款所选的内容
      queryInfo: {quType: '', quBankId: '', quContent: ''},
      //添加题目信息
      formName: {quType: 1, level: 1, quBankId: '', quContent: '', image: '', analysis: '',answer: {allOption: '', images: '', analysis: '', trueOption: ''}},
      formRules: {
        quType: [{required: true, message: '请选择问题类型', trigger: 'blur'}],
        level: [{required: true, message: '请选择问题难度', trigger: 'blur'}],
        quBankId: [{required: true, message: '请选择题库', trigger: 'blur'}],
        quContent: [{required: true, message: '请输入题库内容', trigger: 'blur'}],
      },
      quType: [{id: 1, name: '单选题',}, {id: 2, name: '多选题',}, {id: 3, name: '判断题',}, {id: 4, name: '简答题',}],
      //用来封装添加答案
      answers: [],
      optionArr: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      //更新题目的数据信息
      updateQuestionForm: {id: '', quType: 1, level: 1, quBankId: '', quContent: '', image: '', analysis: '', allOption: '', answerImages: '', answerAnalysis: '', trueOption: ''},
      updateQuestionFormRules: {
        quType: [{required: true, message: '请选择问题类型', trigger: 'blur'}],
        level: [{required: true, message: '请选择问题难度', trigger: 'blur'}],
        quBankId: [{required: true, message: '请选择题库', trigger: 'blur'}],
        quContent: [{required: true, message: '请输入题库内容', trigger: 'blur'}],
      },
      updateAnswers: [],
      //用来拆分的数组
      answersArr: {answerAnalysis: '', allOptionArr: [], analysisArr: []},
      //删除数据表单
      deleteFromId: [],
      //删除等试题管理下拉框的数据
      optionInfo1: [{'label': '批量删除', 'desc': 'delete'},{'label': '正在研发中...', 'desc': 'development'}],
    }
  },

  methods: {
    //后期有需求在添加图片功能
    developed(){
      this.$message({
        message: '正在研发中...',
        type: 'warning',
      });
    },
    //上传成功时图片
    handleSuccess(response, file) {
      if (this.answerImage==""){
        this.answerImage = response.url;
        this.answerUrl = true;
        this.$message({
          message: '上传成功',
          type: 'success'
        });
      }else {
        this.answerFile = [];
        this.handleRemove(file, this.answerFile);
        this.answerUrl = true;
        this.answerFile.push({
          name: file.name,
          url: response.url
        });
        this.answerImage = response.url;
        this.$message({
          message: '上传成功',
          type: 'success'
        });
      }

    },
    //删除答案时响应
    handleRemove(file, fileList) {
      this.answerImage = "";
      this.answerUrl = false;
      this.$message({
        message: '删除成功',
        type: 'success'
      });
    },
    //点击时响应图片
    handlePreview(file) {
      if (this.answerUrl) {
        this.answerUrl = false;
        return;
      }
      this.answerUrl = true;
    },
    //删除答案图片时提示
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    //删除题目的表单信息
    handleDelete(id){
      if (id != null) {
        this.deleteFromId = [];
        this.deleteFromId.push(id);
      }

      this.$confirm('将永久删除此题目,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = 'http://localhost:9282/question/' + this.deleteFromId + '/delete';
        let localJwt = localStorage.getItem('localJwt');
        this.axios.create({
          'headers': {
            'Authorization': localJwt
          }//获取登录时获取的唯一票号，用来表示登录状态，否则是未登录状态
        }).post(url).then((response) => {
          let jsonResult = response.data;
          if (jsonResult.state == 20000) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.questionList();
            if (jsonResult.jwt!=null){
              localStorage.setItem("localJwt",jsonResult.jwt);
            }
          }else if(jsonResult.state==70100){
            this.$alert(jsonResult.message, '错误', {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
            this.$router.push('/')
          } else if (jsonResult.state == 40400) {
            this.$alert(jsonResult.message, '删除失败', {
              confirmButtonText: '确定',
              callback: action => {
                this.questionList();
              }
            })
          } else {
            this.$alert(jsonResult.message, '删除失败', {
              confirmButtonText: '确定',
              callback: action => {
              }
            });
          }
        });
      }).catch(() => {
      });
    },
    //处理删除等选择框的变化
    operationChange(val) {
      //清空上一次的选择
      this.operation = ''
      let questionIds = []

      if (val === 'delete' && this.localUser.roleId == 3){
        this.$message({
          message: '你当前权限不足,不能进行批量删除',
          type: 'warning',
        });
      }

      if (val === 'delete' && this.localUser.roleId != 3) {
        this.selectionTable.map(item => {
          questionIds.push(item.id)
          this.deleteFromId = questionIds;
        })

        this.handleDelete(null);
      }if (val === 'development'){
        //后期有需求在添加其它功能
        this.$message({
          message: '正在研发中...',
          type: 'warning',
        });
      }
    },

    //处理表格被选中
    handleTableSectionChange(val) {
      this.selectionTable = val
    },

    //更新题目中的删除答案填写框
    delUpdateAnswer(id) {//当前答案的id
      this.updateAnswers.map((item, index) => {
        if (item.id === id) this.updateAnswers.splice(index, 1)
      })
    },
    //更新题目中的新增答案填写框
    addUpdateAnswer() {
      if (this.updateQuestionForm.quType === 3) {
        if (this.updateAnswers.length >= 2) {
          this.$message({
            message: '判断题只能有俩项',
            type: 'warning'
          });
          return;
        }
      }
      this.updateAnswers.push({
        id: this.updateAnswers.length,
        isTrue: false,
        answerOne: '',
        images: '',
        analysis: '',
      })
    },
    //提交更新表单
    updateQuestion(updateQuestionForm) {
      this.$refs[updateQuestionForm].validate((valid) => {
        if (valid) {
          if (this.updateQuestionForm.quType === 3) {
            if (this.updateAnswers.length != 2) {
              this.$message({
                message: '判断题只能有俩项',
                type: 'warning'
              });
              return;
            }
          }

          if (this.updateQuestionForm.quType === 1) {
            if (this.updateAnswers.length < 2) {
              this.$message({
                message: '单选题最少有俩项',
                type: 'warning'
              });
              return;
            }
          }

          let allOption = '';
          let analysis = '';
          let trueOption = '';
          let count = '';
          for (let i = 0; i < this.updateAnswers.length; i++) {
            allOption = allOption + this.optionArr[i] + '.' + this.updateAnswers[i].answerOne + "￥&";
            analysis = analysis + this.updateAnswers[i].analysis + "￥&";
            if (this.updateAnswers[i].isTrue == true) {
              if (this.updateQuestionForm.quType == 1 || this.updateQuestionForm.quType == 3) {
                trueOption = this.optionArr[i];
              } else if (this.updateQuestionForm.quType == 2) {
                count += 1;
                trueOption = trueOption + this.optionArr[i] + ',';
              }
            }
          }

          if (this.updateQuestionForm.quType === 2) {
            if (count < 2) {
              this.$message({
                message: '选择题最少勾选俩项',
                type: 'warning'
              });
              return;
            }
          }

          this.updateQuestionForm.image = this.answerImage;

          this.updateQuestionForm.allOption = allOption.substring(0, allOption.length - 2);
          this.updateQuestionForm.answerAnalysis = analysis.substring(0, analysis.length - 2);
          this.updateQuestionForm.trueOption = this.updateQuestionForm.quType == 2 ? trueOption.substring(0, trueOption.length - 1) : trueOption
          this.updateQuestionForm.answerImages = null;//后期需要时在添加图片功能
          console.log("更新答案: " + JSON.stringify(this.updateQuestionForm))

          let url = 'http://localhost:9282/question/update';
          let formData = this.qs.stringify(this.updateQuestionForm);
          this.postUpdateQuestion(url, formData);
        }else if (!valid) {
          this.$message.error('请填写必要信息')
          return false;
        }
      })
    },
    //更新时post请求
    postUpdateQuestion(url, value) {
      this.answerImage = '';
      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({
        'headers': {
          'Authorization': localJwt
        }
      }).post(url, value).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.updateQuTableVisible = false;
          this.answerUrl = false;
          this.questionList();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '修改失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.questionList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '修改失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    //点击更新时显示答案
    showTheAnswer() {
      if (this.updateQuestionForm.image != '') {
        this.answerUrl = true;
        this.answerImage = this.updateQuestionForm.image;
      }

      if (this.updateQuestionForm.quType == 4) {
        return;
      }
      this.updateAnswers = [];
      while (this.updateQuestionForm.allOption.indexOf('￥&') != -1) {
        this.answersArr.allOptionArr = this.updateQuestionForm.allOption.split('￥&');
        this.answersArr.analysisArr = this.updateQuestionForm.answerAnalysis.split('￥&');
        break;
      }
      if (this.updateQuestionForm.quType != 4) {
        for (let i = 0; i < this.answersArr.allOptionArr.length; i++) {
          this.updateAnswers.push({
            id: i,
            isTrue: this.updateQuestionForm.trueOption.includes(this.answersArr.allOptionArr[i].split('.')[0]) ? true : false,
            answerOne: this.answersArr.allOptionArr[i].split('.')[1],
            images: '',
            analysis: this.answersArr.analysisArr[i],
          })
        }
      }
    },
    //点击题目内容刷新题目
    updateQu(question) {
      let url = 'http://localhost:9282/question/standard?id=' + question.id;
      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({
        'headers': {
          'Authorization': localJwt
        }
      }).get(url).then((response) => {
        let jsonResult = response.data
        if (jsonResult.state == 20000) {
          this.updateQuestionForm = jsonResult.data;
          this.updateQuTableVisible = true
          this.showTheAnswer();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确认',
            callback: action => {
              this.questionList();
            }
          })
        }
      });
    },

    //处理分页
    changePage(value) {
      this.$router.replace('?page=' + value);
      this.questionList();
    },
    //点击弹框的x或取消时响应
    beforeClose(is){
      this.updateQuTableVisible=false;
      this.answerImage='';
      this.answerFile = [];
      this.answerUrl = false;
      this.addNewTopice = false;
      if (is==0){
        this.resetForm('formName');
      }
    },

    //新增或更新时选择正确答案的按钮变化事件
    checkAnswer(checked, id) {
      //添加时
      if (checked) {
        if (this.formName.quType === 1 || this.formName.quType === 3) {//单选或者判断
          //当前已经有一个正确的选择了
          this.answers.map(item => {
            item.isTrue = false
          })
          this.answers.map(item => {
            if (item.id === id) item.isTrue = true
          })
        } else {//多选 可以有多个答案
          this.answers.map(item => {
            if (item.id === id) item.isTrue = true
          })
        }
      } else {
        this.answers.map(item => {
          if (item.id === id) item.isTrue = false
        })
      }
      //更新时
      if (checked) {
        if (this.updateQuestionForm.quType === 1 || this.updateQuestionForm.quType === 3) {//单选或者判断
          //当前已经有一个正确的选择了
          this.updateAnswers.map(item => {
            item.isTrue = false
          })
          this.updateAnswers.map(item => {
            if (item.id === id) item.isTrue = true
          })
        } else {//多选 可以有多个答案
          this.updateAnswers.map(item => {
            if (item.id === id) item.isTrue = true
          })
        }
      } else {
        this.updateAnswers.map(item => {
          if (item.id === id) item.isTrue = false
        })
      }
    },
    //新增题目中的删除答案填写框
    delAnswer(id) {//当前答案的id
      this.answers.map((item, index) => {
        if (item.id === id) this.answers.splice(index, 1)
      })
    },
    //新增题目中的新增答案填写框
    addAnswer() {
      if (this.formName.quType === 3) {
        if (this.answers.length >= 2) {
          this.$message({
            message: '判断题只能有俩项',
            type: 'warning'
          });
          return;
        }
      }
      this.answers.push({
        id: this.answers.length,
        isTrue: false,
        answerOne: '',
        images: '',
        analysis: '',
      })
    },
    //点击添加题目弹框
    addTopic() {
      this.addNewTopice = true;
    },
    //重置新增内容
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.answers = [];
      this.answerUrl = false;
      this.answerImage = '';
      this.answerFile = [];
    },
    //添加题目
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.answers.some(item => item.isTrue) && this.formName.quType !== 4) {//单选或者多选或者判断

          if (this.formName.quType === 3) {
            if (this.answers.length != 2) {
              this.$message({
                message: '判断题只能有俩项',
                type: 'warning'
              });
              return;
            }
          }

          if (this.formName.quType === 1) {
            if (this.answers.length < 2) {
              this.$message({
                message: '单选题最少俩项',
                type: 'warning'
              });
              return;
            }
          }

          let allOption = '';
          let analysis = '';
          let trueOption = '';
          let count = '';
          for (let i = 0; i < this.answers.length; i++) {
            allOption = allOption + this.optionArr[i] + '.' + this.answers[i].answerOne + "￥&";
            analysis = analysis + this.answers[i].analysis + "￥&";
            if (this.answers[i].isTrue == true) {
              if (this.formName.quType == 1 || this.formName.quType == 3) {
                trueOption = this.optionArr[i];
              } else if (this.formName.quType == 2) {
                count += 1;
                trueOption = trueOption + this.optionArr[i] + ',';
              }
            }
          }

          if (this.formName.quType === 2) {
            if (count < 2) {
              this.$message({
                message: '多选题最少勾选俩项',
                type: 'warning'
              });
              return;
            }
          }

          this.formName.image = this.answerImage;

          this.formName.answer.allOption = allOption.substring(0, allOption.length - 2);
          this.formName.answer.analysis = analysis.substring(0, analysis.length - 2);
          this.formName.answer.trueOption = this.formName.quType == 2 ? trueOption.substring(0, trueOption.length - 1) : trueOption;
          this.formName.answer.images = null;//后期需要时在添加图片功能
          console.log("答案: " + JSON.stringify(this.formName.answer))

          let url = 'http://localhost:9282/question/add-new'
          this.postQuestion(url, this.formName);

        } else if (valid && !this.answers.some(item => item.isTrue) && this.formName.quType !== 4) {//无答案
          this.$message.error('必须有一个答案');
          return false
        } else if (valid && this.formName.quType === 4) {//简答题 无标准答案直接发请求
          let url = 'http://localhost:9282/question/add-new';
          this.postQuestion(url, this.formName);
        } else if (!valid) {
          this.$message.error('请填写必要信息')
          return false;
        }
      });
    },
    //post发添加请求
    postQuestion(url, value) {
      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({
        'headers': {
          'Authorization': localJwt
        }
      }).post(url, value).then((response) => {
        let jsonResult = response.data
        if (jsonResult.state == 20000) {
          this.$message({
            message: '添加成功',
            type: 'success',
          });
          this.addNewTopice = false;
          this.resetForm('formName');
          this.questionList();
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        } else {
          this.$alert(jsonResult.message, '添加失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.questionList();
            }
          });
        }
      });
    },

    //从数据库中查询题库
    questionBankList() {
      let url = 'http://localhost:9282/bank/listQuestionBank';
      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({
        'headers': {
          'Authorization': localJwt
        }
      }).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.allBank = jsonResult.data;
          if (this.bankId!=0){
            for (let i = 0; i < this.allBank.length; i++) {
              if (this.allBank[i].bankId==this.bankId){
                this.bankName = this.allBank[i].bankName;
              }
            }
          }
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    //从数据库中查询题目的所有信息和分页
    questionList() {
      //判断是否为管理员
      this.localUser = JSON.parse(localStorage.getItem("localUser"));
      let majorId = 0;
      if (this.localUser.roleId == 3) {
        this.isEdit = true;
        majorId = this.localUser.majorId;
      }

      //再网页栏中获取id
      this.bankId = new URLSearchParams(location.search).get("bankId");
      if (this.bankId == null) {
        this.bankId = 0;
      } else {
        this.isBank = true;
      }

      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }

      let quType = 0;
      let quBankId = 0;
      if (this.queryInfo.quType != '') {
        quType = this.queryInfo.quType;
      }

      if (this.queryInfo.quBankId != '') {
        quBankId = this.queryInfo.quBankId;
      }

      let url = 'http://localhost:9282/question/' + this.bankId + '/' + page + '/' + quType + '/' + quBankId + '/'+ majorId+ '/list?quContent=' + this.queryInfo.quContent;
      console.log("查询分页时路径: " + url)
      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({
        'headers': {
          'Authorization': localJwt
        }
      }).get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.questionInfo = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
          if (jsonResult.jwt!=null){
            localStorage.setItem("localJwt",jsonResult.jwt);
          }
        }else if(jsonResult.state==70100){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
          this.$router.push('/')
        }  else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
  },

  mounted() {
    this.questionList();//从数据库中查询题库方法
    this.questionBankList();//从数据库中查询题目的所有信息和分页
  }
}
</script>

